package io.gitee.zhangbinhub.admin.adminserver.component

import de.codecentric.boot.admin.server.config.AdminServerProperties
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler
import org.springframework.stereotype.Component

@Component
class WebSecurityConfiguration @Autowired
constructor(adminServerProperties: AdminServerProperties) {
    private val adminContextPath: String = adminServerProperties.contextPath

    /**
     * http 验证策略配置
     *
     * @param http http 安全验证对象
     * @throws Exception 异常
     */
    @Bean
    @Throws(Exception::class)
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        val successHandler = SavedRequestAwareAuthenticationSuccessHandler()
        successHandler.setTargetUrlParameter("redirectTo")
        successHandler.setDefaultTargetUrl("$adminContextPath/")
        return http.csrf().disable().authorizeRequests { authorize ->
            authorize.antMatchers(
                "$adminContextPath/assets/**",
                "$adminContextPath/instances",
                "$adminContextPath/instances/**",
                "$adminContextPath/actuator",
                "$adminContextPath/actuator/**",
                "$adminContextPath/login",
                "$adminContextPath/error",
                "$adminContextPath/webjars/**",
                "$adminContextPath/notifications/**",
                "$adminContextPath/proxy.stream"
            ).permitAll().anyRequest().authenticated().and()
                .formLogin().loginPage("$adminContextPath/login").successHandler(successHandler).and()
                .logout().logoutUrl("$adminContextPath/logout")
        }.build()
    }
}